<template>
  <div class="other-income-container">
    <!-- 顶部信息栏 -->
    <div class="header-section bg-white rounded-lg shadow-md p-6 mb-6">
      <div
        class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
      >
        <!-- 左侧：客户、业务员、日期 -->
        <div class="flex flex-col gap-4">
          <!-- 客户 -->
          <div class="flex items-center gap-2">
            <label class="required text-gray-700 font-medium">客户：</label>
            <el-input
              v-model="selectedCustomer.name"
              readonly
              @click="customerDialogVisible = true"
              class="w-40 cursor-pointer"
            />
          </div>

          <!-- 业务员 -->
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">业务员：</label>
            <el-select
              v-model="salesman"
              class="w-32"
              @change="handleSalesmanChange"
            >
              <el-option
                v-for="item in salesmanOptions"
                :key="item"
                :label="item"
                :value="item"
              />
              <el-option label="新增职员" value="__new__" />
            </el-select>
          </div>

          <!-- 日期 -->
          <div class="flex items-center gap-4">
            <div class="flex items-center gap-2">
              <label class="required text-gray-700 font-medium"
                >单据日期：</label
              >
              <el-date-picker
                v-model="docDate"
                value-format="YYYY-MM-DD"
                class="w-32"
              />
            </div>
            <div class="flex items-center gap-2">
              <label class="text-gray-700 font-medium">收款到期日：</label>
              <el-date-picker
                v-model="dueDate"
                value-format="YYYY-MM-DD"
                class="w-32"
              />
            </div>
          </div>
        </div>

        <!-- 右侧：附件、单据编号 -->
        <div class="flex flex-col gap-2">
          <el-upload
            action="#"
            :file-list="attachments"
            @preview="handlePreview"
          >
            <el-button
              type="text"
              class="text-blue-600 hover:text-blue-800 flex items-center"
            >
              <el-icon><UploadFilled /></el-icon>
              <span class="ml-1">上传附件</span>
            </el-button>
          </el-upload>
          <span class="text-gray-600">单据编号：{{ docNo }}</span>
        </div>
      </div>
    </div>

    <!-- 收入表格 -->
    <div class="table-section bg-white rounded-lg shadow-md p-6 mb-6">
      <el-table
        :data="tableData"
        border
        stripe
        class="text-sm"
        style="width: 100%; min-width: 800px"
      >
        <!-- 操作列：添加/删除行 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="flex items-center justify-center gap-1">
              <el-button
                type="success"
                size="mini"
                @click="addTableRow(scope.$index)"
                class="px-2 py-1"
                >添加</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteTableRow(scope.row)"
                class="px-2 py-1"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收入类别" prop="incomeType" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.incomeType" size="small" required>
              <el-option
                v-for="item in incomeTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount" width="100" align="right">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.amount"
              type="number"
              size="small"
              required
              step="0.01"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200" />
        <!-- 合计行 -->
        <template #footer>
          <el-table-row class="bg-yellow-100">
            <el-table-cell>合计：</el-table-cell>
            <el-table-cell colspan="2" align="right">
              ¥{{ totalAmount.toFixed(2) }}
            </el-table-cell>
          </el-table-row>
        </template>
      </el-table>
    </div>

    <!-- 底部信息区 -->
    <div class="bottom-section bg-white rounded-lg shadow-md p-6">
      <el-form label-width="80px">
        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            v-model="remark"
            placeholder="暂无备注信息"
            class="h-16"
          />
        </el-form-item>
        <div
          class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
        >
          <div class="flex items-center gap-4">
            <el-form-item label="结算账户">
              <el-select v-model="settleAccount" class="w-32">
                <el-option
                  v-for="item in settleAccountOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="收款金额">
              <el-input
                v-model.number="receiptAmount"
                type="number"
                size="small"
                step="0.01"
              />
            </el-form-item>
            <el-form-item label="本次欠款">
              <el-input
                v-model.number="currentArrears"
                type="number"
                size="small"
                readonly
              />
            </el-form-item>
          </div>
          <div class="flex gap-2">
            <el-button type="primary" class="text-sm">保存并新增</el-button>
            <el-button type="success" class="text-sm">保存</el-button>
            <el-button type="info" class="text-sm">审核</el-button>
            <el-button type="text" class="text-sm text-gray-600"
              >历史单据</el-button
            >
            <el-button type="text" class="text-sm text-gray-600"
              >操作日志</el-button
            >
          </div>
        </div>
      </el-form>
    </div>

    <!-- 选择客户弹窗 -->
    <el-dialog
      title="选择客户"
      v-model="customerDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-form :model="customerQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="类别">
          <el-cascader
            v-model="customerQuery.categoryPath"
            :options="customerCategoryOptions"
            :props="{
              expandTrigger: 'hover',
              value: 'value',
              label: 'label',
              children: 'children',
            }"
            size="small"
          />
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="customerQuery.keyword"
            placeholder="编号/名称/联系人/电话"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="customerQuery.showDisabled" size="small">
            显示禁用客户
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCustomers" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="customerList"
        border
        stripe
        @selection-change="handleCustomerSelection"
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="类别" prop="category" width="100" />
        <el-table-column label="编号" prop="code" width="120" />
        <el-table-column label="名称" prop="name" width="180" />
        <el-table-column label="联系人" prop="contact" width="100" />
        <el-table-column label="手机" prop="phone" width="120" />
        <el-table-column label="备注" prop="remark" width="150" />
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (customerPageSize = val)"
          @current-change="(val) => (customerPage = val)"
          :current-page="customerPage"
          :page-sizes="[10, 50, 100]"
          :page-size="customerPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="customerTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button @click="customerDialogVisible = false" size="small"
            >取消</el-button
          >
          <el-button type="primary" @click="confirmCustomer" size="small"
            >确定</el-button
          >
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
            @click="addCustomerDialogVisible = true"
            >新增客户</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 新增客户弹窗 -->
    <el-dialog
      title="新增客户"
      v-model="addCustomerDialogVisible"
      width="600px"
      class="dialog-custom"
    >
      <el-form :model="newCustomer" label-width="100px" class="p-4">
        <el-form-item label="*类别" prop="category">
          <el-input v-model="newCustomer.category" size="small" required />
        </el-form-item>
        <el-form-item label="*编号" prop="code">
          <el-input v-model="newCustomer.code" size="small" required />
        </el-form-item>
        <el-form-item label="*名称" prop="name">
          <el-input v-model="newCustomer.name" size="small" required />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="newCustomer.contact" size="small" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="newCustomer.phone" size="small" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="newCustomer.remark" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addCustomerDialogVisible = false" size="small"
            >取消</el-button
          >
          <el-button type="primary" @click="saveNewCustomer" size="small"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 新增职员弹窗 -->
    <el-dialog
      title="新增职员"
      v-model="newStaffDialogVisible"
      width="500px"
      class="dialog-custom"
    >
      <el-form :model="newStaff" label-width="100px" class="p-4">
        <el-form-item label="*职员编号" prop="code">
          <el-input v-model="newStaff.code" size="small" required />
        </el-form-item>
        <el-form-item label="*职员名称" prop="name">
          <el-input v-model="newStaff.name" size="small" required />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="newStaff.phone" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="newStaffDialogVisible = false" size="small"
            >关闭</el-button
          >
          <el-button type="primary" @click="saveNewStaff" size="small"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElUpload,
  ElMessage,
  ElIcon,
  ElCascader,
} from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";

// 防抖函数（核心优化：避免表格频繁更新触发 ResizeObserver 错误）
const debounce = (fn, delay = 100) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
};

// 客户相关数据
const selectedCustomer = ref({ name: "" });
const customerDialogVisible = ref(false);
const customerQuery = reactive({
  categoryPath: [], // 级联类别路径
  keyword: "",
  showDisabled: false,
});
const customerCategoryOptions = ref([
  { label: "广东省内", value: "guangdong" },
  {
    label: "华北地区",
    value: "north",
    children: [
      { label: "零售", value: "north-retail" },
      { label: "批发", value: "north-wholesale" },
    ],
  },
  {
    label: "华东地区",
    value: "east",
    children: [{ label: "批发", value: "east-wholesale" }],
  },
  { label: "华南地区", value: "south" },
  { label: "华中地区", value: "central" },
]);
const customerList = ref([
  {
    category: "华中地区",
    code: "1000000",
    name: "客户1",
    contact: "张",
    phone: "159****1234",
    remark: "",
  },
  {
    category: "华北地区",
    code: "1000001",
    name: "客户2",
    contact: "李先生",
    phone: "183****0000",
    remark: "",
  },
  {
    category: "华北地区",
    code: "1000002",
    name: "客户3",
    contact: "王",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "华南地区",
    code: "1000003",
    name: "客户4-罗",
    contact: "赵",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "批发",
    code: "1000004",
    name: "客户5",
    contact: "马路",
    phone: "183****0000",
    remark: "",
  },
  {
    category: "广东省内",
    code: "1000005",
    name: "客户6",
    contact: "周",
    phone: "180****0000",
    remark: "",
  },
  {
    category: "华中地区",
    code: "1000006",
    name: "客户7",
    contact: "吴",
    phone: "182****1234",
    remark: "",
  },
  {
    category: "批发",
    code: "1000007",
    name: "客户8",
    contact: "郑",
    phone: "159****1234",
    remark: "",
  },
  {
    category: "华中地区",
    code: "1000008",
    name: "客户9",
    contact: "王",
    phone: "175****1234",
    remark: "",
  },
]);
const customerTotal = ref(17);
const customerPage = ref(1);
const customerPageSize = ref(10);
const newCustomer = reactive({
  category: "",
  code: "",
  name: "",
  contact: "",
  phone: "",
  remark: "",
});
const addCustomerDialogVisible = ref(false);

// 职员相关数据
const salesmanOptions = ref([
  "(空)",
  "老板",
  "财务-玲",
  "采购-小陈",
  "采购-小王",
  "销售-小李",
]);
const salesman = ref("(空)");
const newStaff = reactive({
  code: "",
  name: "",
  phone: "",
});
const newStaffDialogVisible = ref(false);

// 单据信息
const docDate = ref(new Date().toISOString().slice(0, 10));
const dueDate = ref("");
const docNo = ref("QTSR20250625001");
const attachments = ref([]);
const remark = ref("");

// 表格数据
const incomeTypeOptions = ref(["销售收入", "服务收入", "其他"]);
const tableData = ref([
  {
    id: 1,
    incomeType: "",
    amount: 0,
    remark: "",
  },
]);
const totalAmount = computed(() =>
  tableData.value.reduce((sum, item) => sum + item.amount, 0)
);

// 防抖更新表格数据（核心优化）
const updateTable = debounce((newData) => {
  tableData.value = newData;
});

// 表格操作方法
const addTableRow = (index) => {
  const newRow = {
    id: tableData.value.length + 1,
    incomeType: "",
    amount: 0,
    remark: "",
  };
  const newData = [...tableData.value];
  newData.splice(index + 1, 0, newRow);
  updateTable(newData);
};
const deleteTableRow = (row) => {
  const newData = tableData.value.filter((item) => item.id !== row.id);
  updateTable(newData);
};

// 结算信息
const settleAccountOptions = ref(["1002 银行存款", "1001 库存现金"]);
const settleAccount = ref("1002 银行存款");
const receiptAmount = ref(0);
const currentArrears = computed(() => totalAmount.value - receiptAmount.value);

// 客户交互方法
const fetchCustomers = () => {
  console.log("查询客户参数：", customerQuery);
};
const handleCustomerSelection = (val) => {
  selectedCustomer.value = val[0] || {};
};
const confirmCustomer = () => {
  customerDialogVisible.value = false;
};
const saveNewCustomer = () => {
  if (!newCustomer.category || !newCustomer.code || !newCustomer.name) {
    ElMessage.warning("类别、编号、名称为必填项！");
    return;
  }
  customerList.value.push({ ...newCustomer });
  ElMessage.success("客户添加成功！");
  addCustomerDialogVisible.value = false;
};

// 职员交互方法
const handleSalesmanChange = (val) => {
  if (val === "__new__") {
    newStaffDialogVisible.value = true;
    salesman.value = "(空)"; // 重置选择
  }
};
const saveNewStaff = () => {
  if (!newStaff.code || !newStaff.name) {
    ElMessage.warning("职员编号、名称为必填项！");
    return;
  }
  salesmanOptions.value.push(newStaff.name); // 简单更新选项
  ElMessage.success("职员添加成功！");
  newStaffDialogVisible.value = false;
};

// 附件预览
const handlePreview = (file) => {
  ElMessage.info(`预览附件：${file.name}`);
};

onMounted(() => {
  fetchCustomers();
});
</script>

<style scoped>
.other-income-container {
  padding: 32px;
  background: #f9fafb;
}
.header-section,
.table-section,
.bottom-section {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}
.required::after {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.el-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #f5f7fa;
  --el-table-row-hover-background-color: #f0f2f5;
}
.el-table__cell {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
}
.overflow-x-auto {
  overflow-x: auto;
}
::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
@media (max-width: 1024px) {
  .other-income-container {
    padding: 16px;
  }
  .header-section .flex {
    flex-direction: column;
    gap: 4px;
  }
  .header-section .flex > div {
    min-width: 100%;
  }
}
</style>